package com.fysports.web.kit.dtgrid;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Page;
import com.fysports.framework.exception.FrameException;
import com.fysports.web.kit.commons.StringKit;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Dtgrid 控件工具类<br/>
 * <p/>
 * 1.build传入前端的参数对象DTGridView <br/>
 * 2.通过Request中参数构建DTGridView <br/>
 * <p/>
 * Created by konbluesky <br/>
 * Date : 15/11/17 下午1:57 <br/>
 * Project : jdmdataServer <br/>
 */
public class DTGridKit {
    /**
     * 前台JS控件 传参名称
     */
    public static String PARAM_NAME = "dtGridPager";

    private static Log log = Log.getLog(DTGridKit.class);
    /**
     * 工具对象，保证全局唯一
     */
    private static Gson gson = new Gson();

    /**
     * Querytype:fast or Advance
     */
    public static int TYPE_FASTQUERY = 1;
    public static int TYPE_ADVANCEQUERY = 2;


    /**
     * json字符串转Dtgrid view
     *
     * @param jsonstr 字符串
     * @return DTGridView
     * @throws JsonSyntaxException
     */
    public static DTGridView toDtView(String jsonstr) {
        Preconditions.checkArgument(jsonstr != null && jsonstr.length() > 0, "json 数据不能为空");
        DTGridView dt = null;
        try {
            dt = gson.fromJson(jsonstr, DTGridView.class);
        }
        catch (JsonSyntaxException e) {
            log.debug("jsonstr:" + jsonstr);
            log.error("dtgrid json 数据解析失败", e);
            throw new FrameException(e.getLocalizedMessage(),e);
        }
        List<Object> args = Lists.newArrayList();
//        System.out.println("===========" + getAdvanceQueryConditionSql(dt.getAdvanceQueryConditions(), args));
//        System.out.println("===========||||" + getFastQuerySql(dt.getFastQueryParameters(), args));
        return dt;
    }


    /**
     * 根据jfinal中pager对象构建DTGridView对象
     *
     * @param pager
     * @return
     */
    public static DTGridView toDtView(DTGridView dt,Page<?> pager) {
        //总页数
        dt.setPageCount(pager.getTotalPage());
        //当页记录条数
        dt.setPageSize(pager.getPageSize());
        //当前页码
        dt.setNowPage(pager.getPageNumber());
        //总记录条数
        dt.setRecordCount(pager.getTotalRow());
        //记录list
        dt.setExhibitDatas(pager.getList());
        //成功标志
        dt.setIsSuccess(pager.getList().size() > 0 ? true : false);
        return dt;
    }

    /**
     * 获取快速查询的条件SQL
     *
     * @param params    快速查询参数
     * @param arguments 参数值列表
     * @return 条件SQL
     * @throws Exception
     */
    public static String getFastQuerySql(Map<String, Object> params, List<Object> arguments) {
        //		如果传递的条件参数为空则返回空字符串
        if (params == null) {
            return "";
        }
        //		定义条件SQL
        StringBuffer conditionSql = new StringBuffer();
        //		遍历参数，拼接SQL
        for (String key : params.keySet()) {
            /**
             * 修改:前端传来的参数中有[xx_xxx_format] 影响sql生成,暂时过滤
             * "fastQueryParameters":{"rl_phone":"150","rl_phone_format":null,"eq_gender":"","eq_gender_format":null}
             * @Author konbluesky
             */
            if ("".equals(getStrFromMap(params, key, "").trim()) || key.endsWith("_format"))
                continue;
            if (key.indexOf("_") != -1) {
                String field = key.substring(key.indexOf("_") + 1, key.length());
                //				equal
                if (key.startsWith("eq_")) {
                    conditionSql.append(" and ").append(field).append(" = ? ");
                    arguments.add(getStrFromMap(params, key));
                    continue;
                }
                //				not equal
                if (key.startsWith("ne_")) {
                    conditionSql.append(" and ").append(field).append(" != ? ");
                    arguments.add(getStrFromMap(params, key));
                    continue;
                }
                //				like
                if (key.startsWith("lk_")) {
                    conditionSql.append(" and ").append(field).append(" like ? ");
                    arguments.add("%" + getStrFromMap(params, key) + "%");
                    continue;
                }
                //				right like
                if (key.startsWith("rl_")) {
                    conditionSql.append(" and ").append(field).append(" like ? ");
                    arguments.add("%" + getStrFromMap(params, key));
                    continue;
                }
                //				left like
                if (key.startsWith("ll_")) {
                    conditionSql.append(" and ").append(field).append(" like ? ");
                    arguments.add(getStrFromMap(params, key) + "%");
                    continue;
                }
                //				is null
                if (key.startsWith("in_")) {
                    conditionSql.append(" and ").append(field).append(" is null ");
                    continue;
                }
                //				is not null
                if (key.startsWith("inn_")) {
                    conditionSql.append(" and ").append(field).append(" is not null ");
                    continue;
                }
                //				great then
                if (key.startsWith("gt_")) {
                    conditionSql.append(" and ").append(field).append(" > ? ");
                    arguments.add(getStrFromMap(params, key));
                    continue;
                }
                //				great then and equal
                if (key.startsWith("ge_")) {
                    conditionSql.append(" and ").append(field).append(" >= ? ");
                    arguments.add(getStrFromMap(params, key));
                    continue;
                }
                //				less then
                if (key.startsWith("lt_")) {
                    conditionSql.append(" and ").append(field).append(" < ? ");
                    arguments.add(getStrFromMap(params, key));
                    continue;
                }
                //				less then and equal
                if (key.startsWith("le_")) {
                    conditionSql.append(" and ").append(field).append(" <= ? ");
                    arguments.add(getStrFromMap(params, key));
                    continue;
                }
            }
        }
        //		返回条件SQL
        return conditionSql.toString();
    }


    /**
     * 获取高级查询的条件SQL
     *
     * @param advanceQueryConditions 查询条件列表
     * @param arguments              参数值列表
     * @return 条件SQL
     * @throws Exception
     */
    public static String getAdvanceQueryConditionSql(List<Condition> advanceQueryConditions,
            List<Object> arguments) {
        //		定义条件SQL
        StringBuffer conditionSql = new StringBuffer();
        if (advanceQueryConditions != null && advanceQueryConditions.size() > 0) {
            //			加入前置的and参数
            conditionSql.append(" and ");
            for (Condition advanceQueryCondition : advanceQueryConditions) {
                //				获取参数：leftParentheses-左括号 field-字段名 condition-条件 value-值 rightParentheses-右括号 logic-逻辑符号
                String leftParentheses = advanceQueryCondition.getLeftParentheses();
                String field = advanceQueryCondition.getField();
                String condition = advanceQueryCondition.getCondition();
                String value = advanceQueryCondition.getValue();
                String rightParentheses = advanceQueryCondition.getRightParentheses();
                String logic = advanceQueryCondition.getLogic();
                //				拼接SQL
                getSingleAdvanceQueryConditionSql(conditionSql, leftParentheses, field, condition, value,
                        rightParentheses, logic, arguments);
            }
        }
        //		返回条件SQL
        return conditionSql.toString();
    }


    /**
     * 拼接单条的高级查询SQL
     *
     * @param conditionSql     条件SQL
     * @param leftParentheses  左括号 0-( 1-(( 2-((( 3-(((( 4-(((((
     * @param field            字段信息
     * @param condition        条件 0-= 1-!= 2-like 3-start with 4-end with 5-> 6->= 7-< 8-<= 9-is null 10-is not null
     * @param value            值
     * @param rightParentheses 右括号 0-) 1-)) 2-))) 3-)))) 4-)))))
     * @param logic            逻辑符号 0-and 1-or
     * @param arguments        参数值列表
     */
    private static void getSingleAdvanceQueryConditionSql(StringBuffer conditionSql, String leftParentheses,
            String field, String condition, String value, String rightParentheses, String logic,
            List<Object> arguments) {
        //		获取左括号内容、右括号内容、逻辑符号内容
        logic = getConditionLogicContent(logic);
        //		根据条件类型拼接SQL
        conditionSql.append(" ").append(leftParentheses).append(" ");
        if ("0".equals(condition)) {
            conditionSql.append(" ").append(field).append(" = ? ");
            arguments.add(value);
        }
        else if ("1".equals(condition)) {
            conditionSql.append(" ").append(field).append(" != ? ");
            arguments.add(value);
        }
        else if ("2".equals(condition)) {
            conditionSql.append(" ").append(field).append(" like ? ");
            arguments.add("%" + value + "%");
        }
        else if ("3".equals(condition)) {
            conditionSql.append(" ").append(field).append(" like ? ");
            arguments.add(value + "%");
        }
        else if ("4".equals(condition)) {
            conditionSql.append(" ").append(field).append(" like ? ");
            arguments.add("%" + value);
        }
        else if ("5".equals(condition)) {
            conditionSql.append(" ").append(field).append(" > ? ");
            arguments.add(value);
        }
        else if ("6".equals(condition)) {
            conditionSql.append(" ").append(field).append(" >= ? ");
            arguments.add(value);
        }
        else if ("7".equals(condition)) {
            conditionSql.append(" ").append(field).append(" < ? ");
            arguments.add(value);
        }
        else if ("8".equals(condition)) {
            conditionSql.append(" ").append(field).append(" <= ? ");
            arguments.add(value);
        }
        else if ("9".equals(condition)) {
            conditionSql.append(" ").append(field).append(" is null ");
        }
        else if ("10".equals(condition)) {
            conditionSql.append(" ").append(field).append(" is not null ");
        }
        conditionSql.append(" ").append(rightParentheses).append(" ");
        conditionSql.append(" ").append(logic).append(" ");
    }


    /**
     * 获取逻辑内容
     *
     * @param logic 逻辑码值
     * @return 逻辑内容
     */
    private static String getConditionLogicContent(String logic) {
        String content = "";
        if ("0".equals(logic)) {
            content = "and";
        }
        else if ("1".equals(logic)) {
            content = "or";
        }
        return content;
    }


    /**
     * 获取高级查询的排序SQL
     *
     * @param advanceQuerySorts 排序列表
     * @return 条件SQL
     * @throws Exception
     */
    public static String getAdvanceQuerySortSql(List<Sort> advanceQuerySorts) {
        //		定义条件SQL
        StringBuffer sortSql = new StringBuffer();
        if (advanceQuerySorts != null && advanceQuerySorts.size() > 0) {
            //			加入前置的and参数
            sortSql.append(" order by ");
            for (Sort advanceQuerySort : advanceQuerySorts) {
                //				获取参数：field-字段名 logic-排序逻辑
                String field = advanceQuerySort.getField();
                String logic = advanceQuerySort.getLogic();
                //				拼接SQL
                getSingleAdvanceQuerySortSql(sortSql, field, logic);
            }
            sortSql.delete(sortSql.lastIndexOf(","), sortSql.length());
        }
        //		返回条件SQL
        return sortSql.toString();
    }


    /**
     * 拼接单条的高级排序SQL
     *
     * @param sortSql 排序SQL
     * @param field   字段信息
     * @param logic   逻辑符号 0-asc 1-desc
     */
    private static void getSingleAdvanceQuerySortSql(StringBuffer sortSql, String field, String logic) {
        //		获取左括号内容、右括号内容、逻辑符号内容
        logic = getSortLogicContent(logic);
        //		根据条件类型拼接SQL
        sortSql.append(" ").append(field).append(" ").append(logic).append(",  ");
    }


    /**
     * 获取排序逻辑内容
     *
     * @param logic 逻辑码值
     * @return 逻辑内容
     */
    private static String getSortLogicContent(String logic) {
        String content = "";
        if ("0".equals(logic)) {
            content = "asc";
        }
        else if ("1".equals(logic)) {
            content = "desc";
        }
        return content;
    }


    /**
     * 替换原类中引用的 MapUtils.getString;
     *
     * @param params
     * @param key
     * @param defval
     * @return
     */
    public static String getStrFromMap(Map<String, Object> params, String key, String defval) {
        String result = String.valueOf(params.get(key));
        return StringKit.isBlank(result) ? defval : result;
    }


    public static String getStrFromMap(Map<String, Object> params, String key) {
        return getStrFromMap(params, key, "");
    }


    /**
     * 统一条件获取接口,快速查询&高级查询条件均从此接口获取
     *
     * @param dt
     * @param type TYPE_FASTQUERY ;TYPE_ADVANCEQUERY
     * @return
     */
    public static String getQueryConditionByType(DTGridView dt, List<Object> args, int type) {
        String result = "";
        if (type == TYPE_ADVANCEQUERY) {
            result = getAdvanceQueryConditionSql(dt.getAdvanceQueryConditions(), args);
        }
        else if (type == TYPE_FASTQUERY) {
            result = getFastQuerySql(dt.getFastQueryParameters(), args);
        }
        return result;
    }


    /**
     * 格式化日期
     * 
     * @param column
     * @param content
     * @return
     * @throws Exception
     */
    public static String formatContent(Column column, String content) {
        try {
            // 处理码表
            if (column.getCodeTable() != null) {
                if (column.getCodeTable().containsKey(content)) {
                    return getStrFromMap(column.getCodeTable(), content);
                }
            }
            // 处理日期、数字的默认情况
            if ("date".equalsIgnoreCase(column.getType()) && column.getFormat() != null
                    && !"".equals(column.getFormat())) {
                if (column.getOtype() != null && !"".equals(column.getOtype())) {
                    if ("time_stamp_s".equals(column.getOtype())) {
                        SimpleDateFormat sdf = new SimpleDateFormat(column.getFormat());
                        Date date = new Date(Integer.parseInt(content) * 1000);
                        return sdf.format(date);
                    }
                    else if ("time_stamp_ms".equals(column.getOtype())) {
                        SimpleDateFormat sdf = new SimpleDateFormat(column.getFormat());
                        Date date = new Date(Integer.parseInt(content));
                        return sdf.format(date);
                    }
                    else if ("string".equals(column.getOtype())) {
                        if (column.getOformat() != null && !"".equals(column.getOformat())) {
                            SimpleDateFormat osdf = new SimpleDateFormat(column.getOformat());
                            SimpleDateFormat sdf = new SimpleDateFormat(column.getFormat());
                            Date date = osdf.parse(content);
                            return sdf.format(date);
                        }
                    }
                }
            }
            else if ("number".equalsIgnoreCase(column.getType()) && !"".equals(column.getFormat())) {
                DecimalFormat df = new DecimalFormat(column.getFormat());
                content = df.format(Double.parseDouble(content));
            }
        }
        catch (Exception e) {
            log.error(e.getLocalizedMessage(),e);
            throw new FrameException(e);
        }
        return content;
    }
    

    public static boolean isAdvance(DTGridView dt) {
        return !dt.getAdvanceQueryConditions().isEmpty();
    }


    public static boolean isFast(DTGridView dt) {
        return !dt.getFastQueryParameters().isEmpty();
    }

    //    /**
    //     * 测试main
    //     *
    //     * @param args
    //     */
    //    public static void main(String[] args) {
    //        String data =
    //                "{\"isExport\":false,\"pageSize\":10,\"startRecord\":0,\"nowPage\":1,\"recordCount\":-1,\"pageCount\":-1,\"parameters\":{paramA:9527,\"paramB\":\"abcd\"},\"fastQueryParameters\":{},\"advanceQueryConditions\":[],\"advanceQuerySorts\":[]}";
    //        DTGridView dt = toDtView(data);
    //        System.out.println(dt);
    //        toDtView("");
    //
    //        /*========*/
    //
    //        Map<String,Object> m= Maps.newHashMap();
    //        m.put("key1",1);
    //        m.put("key2","value2");
    //        m.put("key3",true);
    //        System.out.println(getStrFromMap(m, "key1"));
    //        System.out.println(getStrFromMap(m, "key2"));
    //        System.out.println(getStrFromMap(m, "key3"));
    //    }
}
